//
//  ViewController.m
//  SDDemo
//
//  Created by Husn on 2025/4/21.
//

#import "ViewController.h"
#import <SDWebImage.h>
#import "SecondViewController.h"

@interface ViewController ()
@property (nonatomic, strong) SDAnimatedImageView *imageView;
@property (nonatomic, strong) SDAnimatedImageView *imageView2;
@property (nonatomic, strong) CAShapeLayer *progressLayer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 创建imageview
    SDAnimatedImageView *imageView = [[SDAnimatedImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
    imageView.center = self.view.center;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.backgroundColor = [UIColor redColor];
    [self.view addSubview:imageView];
    self.imageView = imageView;
    // 创建圆环进度条
    [self setupProgressLayer];
    
//    SDAnimatedImageView *imageView2 = [[SDAnimatedImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
//    imageView2.contentMode = UIViewContentModeScaleAspectFill;
//    imageView2.backgroundColor = [UIColor redColor];
//    [self.view addSubview:imageView2];
//    self.imageView2 = imageView2;
    // 创建按钮，点击跳转SecondViewController
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:@"跳转" forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 100, 50);
    button.center = CGPointMake(self.view.center.x, self.view.center.y + 150);
    [button addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
    [self selfDecode];
}

- (void)selfDecode {
    NSURL *url = [NSURL URLWithString:@"https://raw.githubusercontent.com/liyong03/YLGIFImage/master/YLGIFImageDemo/YLGIFImageDemo/joy.gif"];
    // 使用SDWebImage加载图片
    SDWebImageOptions options = SDWebImageProgressiveLoad | SDWebImageRetryFailed | SDWebImageDecodeFirstFrameOnly | SDWebImageDecodeAllFramesAfterFinish
    | SDWebImageProgressiveLoadOnlyAnimated;
//    SDWebImageOptions options = SDWebImageProgressiveLoad | SDWebImageRetryFailed | SDWebImageDecodeFirstFrameOnly;
    [self.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"avatar_default"] options:options progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        if (expectedSize > 0) {
            CGFloat progress = (CGFloat)receivedSize / (CGFloat)expectedSize;
            dispatch_async(dispatch_get_main_queue(), ^{
                self.progressLayer.strokeEnd = progress; // 更新进度
            });
            // 打印进度
            NSLog(@"receivedSize: %ld, expectedSize: %ld, Progress: %.2f%%", receivedSize, expectedSize, progress * 100);
        }
    } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
//        [[SDImageCache sharedImageCache] removeImageFromMemoryForKey:imageURL.absoluteString];
//        [self.imageView sd_setImageWithURL:imageURL placeholderImage:image]; // 重置一次缓存策略
//        image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imageURL.absoluteString];
//        self.imageView.image = image;
    }];
}

- (void)testStaticImage {
    NSURL *url = [NSURL URLWithString:@"https://raw.githubusercontent.com/CloudlessMoon/SuperResources/master/Images/JPG/TestHDR1.JPG"];
    // 使用SDWebImage加载图片
    SDWebImageOptions options = SDWebImageProgressiveLoad | SDWebImageProgressiveLoadOnlyAnimated;
    [self.imageView sd_setImageWithURL:url placeholderImage:nil options:options];
}

- (void)decodeFirstOnly {
    NSURL *url = [NSURL URLWithString:@"https://raw.githubusercontent.com/liyong03/YLGIFImage/master/YLGIFImageDemo/YLGIFImageDemo/joy.gif"];
    // 使用SDWebImage加载图片
    SDWebImageOptions options = SDWebImageProgressiveLoad | SDWebImageRetryFailed | SDWebImageDecodeFirstFrameOnly;
    if ([[SDImageCache sharedImageCache] imageFromCacheForKey:url.absoluteString]) { // 从内存缓存中获取图片
        [self.imageView sd_setImageWithURL:url];
    } else {
        [self.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placeholder"] options:options progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
            if (expectedSize > 0) {
                CGFloat progress = (CGFloat)receivedSize / (CGFloat)expectedSize;
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.progressLayer.strokeEnd = progress; // 更新进度
                });
                // 打印进度
                NSLog(@"receivedSize: %ld, expectedSize: %ld, Progress: %.2f%%", receivedSize, expectedSize, progress * 100);
            }
        } completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            [[SDImageCache sharedImageCache] removeImageFromMemoryForKey:imageURL.absoluteString];
            [self.imageView sd_setImageWithURL:imageURL placeholderImage:image]; // 重置一次缓存策略
    //        image = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imageURL.absoluteString];
    //        self.imageView.image = image;
        }];
        
//        [self.imageView sd_setImageWithURL:urlc];
        
        // 1. 列表复用的时候，url下载完成的回调会不会造成视图混乱
        // 2. 当前视图内存回收，下载回调回来会不会造成内存泄露
        // 3. 当前页面出现多个相同的url，回调的时存在多次移除问题
    }
}

- (void)setupProgressLayer {
    CGFloat radius = 100; // 半径
    CGPoint center = self.imageView.center;
    
    UIBezierPath *circlePath = [UIBezierPath bezierPathWithArcCenter:center
                                                             radius:radius
                                                         startAngle:-M_PI_2
                                                           endAngle:(3 * M_PI_2)
                                                          clockwise:YES];
    
    CAShapeLayer *progressLayer = [CAShapeLayer layer];
    progressLayer.path = circlePath.CGPath;
    progressLayer.strokeColor = [UIColor blueColor].CGColor;
    progressLayer.fillColor = [UIColor clearColor].CGColor;
    progressLayer.lineWidth = 5.0;
    progressLayer.strokeEnd = 0.0; // 初始进度为0
    [self.view.layer addSublayer:progressLayer];
    self.progressLayer = progressLayer;
}

- (void)buttonClicked {
    SecondViewController *secondVC = [[SecondViewController alloc] init];
    [self.navigationController pushViewController:secondVC animated:YES];
}
@end
